# 区分易混淆的类型

# 列表 （可变的数据集合）

friuts = ["apple", "pear", "banana"]

print("friuts 1st: %s" % friuts,"\n")

friuts[0] = "changed"
print("friuts 2nd: %s" % friuts,"\n")

# list add item 
friuts.append("orange")
print("friuts 3rd: %s" % friuts,"\n")

# list delete item
friuts.remove("pear")
print("friuts 4th: %s" % friuts,"\n")


# 列表计算
socres = [90, 80, 70, 60]
print("socres sum:", sum(socres), "\n")
print("socres average:", sum(socres)/len(socres), "\n")


# 元组 （不可变的数据集合）(场景：例如用于坐标)
colors = ("red", "green", "black")
print("colors 1st:", colors,"\n")

try:
    colors[0] = "changed"
except TypeError as e:
    print("can not change tuple: %s" % e,"\n")
    
print("colors 2nd:", colors,"\n")

# 字典 （键值对） (字典的kay 必须唯一，不然后者会直接覆盖前者的value)
students = {"name": "alice", "age": "18", "major": "math"}
print("students value:",students)


studentsAge = {
    "alice": "18",
    "bob": "19",
    "charlie": "20"
}

print("students age: ", studentsAge, "\n")

# 通过键访问字典中的值
print(studentsAge["bob"])


# 通过键修改字典中的值
studentsAge["bob"] = "21"
print(studentsAge["bob"])

# 增加
studentsAge["dave"] = "12"
print(studentsAge)

# 删减
del studentsAge["bob"]
print(studentsAge)

# 获取所有的键，组成列表
keys = studentsAge.keys()
print("数据类型", type(keys), "\n","值：", keys, "\n")
# 对其做数据类型转换
keys = list(keys)
print("After Data Type Transfering; keys datatype:", type(keys), keys, "\n")

# 同样获取字典中所有的 value
values = studentsAge.values()
print(values)

items = studentsAge.items()
print(items)

# 转换一下类型
items = list(items)
print("items type:", type(items),"items values:", items, "\n")

# 判断字典
exits = "bob" in studentsAge
print(exits)

# 获取字典的指定键的值，若没有就给予默认值
print(studentsAge.get("dave", 808))
print(studentsAge.get("bob", 808))


# 对字典做迭代
# 遍历所有的键 / 值  / 键值对

for key in studentsAge.keys():
    print(key)

for value in studentsAge.values():
    print(value)

for key, value in studentsAge.items():
    print(key, value)

# 做排序
sortedKeys = sorted(studentsAge.keys(),reverse=True)
print(sortedKeys, type(sortedKeys))

# 将字典，根据键排序
sorteddict = sorted(studentsAge.items())
print(sorteddict, type(sorteddict))

# 此时 sorteddict 数据类型： 以元组为元素的列表


# studentsAge = {
#     "alice": "18",
#     "bob": "19",
#     "charlie": "20"
# }
# 将字典根据键值排序; lamda 函数告诉 sorted 函数，按照什么来排序
# sorted函数接受的参数定义为 key（key=lamda，是在对 key 赋值，（x[1]表示取元组索引为1的元素来排序））
sorteddict = sorted(studentsAge.items(), key=lambda x:x[1])
print(sorteddict, type(sorteddict))

# 再次转换为字典
dict(sorteddict)
print(dict(sorteddict), type(dict(sorteddict)))


# 嵌套字典的操作举例
config  = {
    "database": {
        "host": "localhost",
        "port": 3306,
        "user": "root",
        "password": "123456"
    },
    "redis": {
        "host": "localhost",
        "port": 6379
    }
}

print(config["redis"]["port"])
config["database"]["password"] = "testpass"

print(config)